from sqlalchemy.orm import Session
from app import models, schemas

def get_recipes(db: Session, skip: int = 0, limit: int = 100):
    return db.query(models.Recipe).offset(skip).limit(limit).all()

def get_recipe_by_id(db: Session, recipe_id: int):
    return db.query(models.Recipe).filter(models.Recipe.id == recipe_id).first()

def create_recipe(db: Session, recipe: schemas.RecipeCreate):
    db_recipe = models.Recipe(
        dish_name=recipe.dish_name,
        ingredients=recipe.ingredients,
        method=recipe.method,
        comment=recipe.comment,
        self_critique=recipe.self_critique,
        image_urls=recipe.image_urls if recipe.image_urls else []
    )
    db.add(db_recipe)
    db.commit()
    db.refresh(db_recipe)
    return db_recipe

def delete_recipe(db: Session, recipe_id: int):
    recipe = db.query(models.Recipe).filter(models.Recipe.id == recipe_id).first()
    if recipe:
        db.delete(recipe)
        db.commit()
        return True
    return False

def update_recipe(db: Session, recipe_id: int, recipe_update: schemas.RecipeUpdate):
    recipe = db.query(models.Recipe).filter(models.Recipe.id == recipe_id).first()
    if recipe:
        update_data = recipe_update.model_dump(exclude_unset=True)
        for key, value in update_data.items():
            setattr(recipe, key, value)
        db.commit()
        db.refresh(recipe)
        return recipe
    return None
